import Mock from 'mockjs'

// 从 localStorage 初始化或获取用户数据
const getUsers = () => {
  const data = localStorage.getItem('mock_users')
  return data ? JSON.parse(data) : []
}

// 保存用户数据到 localStorage
const saveUsers = (users) => {
  localStorage.setItem('mock_users', JSON.stringify(users))
}

// 初始化默认用户（仅首次运行）
if (!localStorage.getItem('mock_users')) {
  saveUsers([
    { id: 1, username: 'admin', password: '123456' }
  ])
}

// 登录接口
Mock.mock('/api/login', 'post', (req) => {
  const { username, password } = JSON.parse(req.body)
  const users = getUsers()
  const user = users.find(u => u.username === username && u.password === password)
  
  return user 
    ? { code: 200, message: '登录成功', token: Mock.Random.guid() }
    : { code: 401, message: '用户名或密码错误' }
})

// 注册接口
Mock.mock('/api/register', 'post', (req) => {
  const { username, password } = JSON.parse(req.body)
  const users = getUsers()
  
  if (users.some(u => u.username === username)) {
    return { code: 400, message: '用户名已存在' }
  }
  
  const newUser = {
    id: users.length + 1,
    username,
    password
  }
  
  saveUsers([...users, newUser])
  return { code: 200, message: '注册成功' }
})